package history

import (
	"crypto/md5"
	"encoding/hex"
	"io"
	//"sync"
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type MHistory struct {
	Id             bson.ObjectId "_id"
	Url            string
	State          string
	Md5            string
	LastModifyTime time.Time
}
type MongodbHistory struct {
	//locker *sync.Mutex
}

func NewMongodbHistory() *MongodbHistory {
	return &MongodbHistory{} //locker: new(sync.Mutex)}
}
func (this *MongodbHistory) GetRegisteredCount() int64 {

	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// 获取数据库,获取集合
	c := session.DB("go_spider").C("History")

	// 存储数据

	count, err := c.Count()

	if err != nil {
		println(err.Error())
		panic(err)
	}
	return int64(count)
}
func (this *MongodbHistory) Register(url string) bool {
	var result bool = false
	//this.locker.Lock()
	//defer this.locker.Unlock()
	t := md5.New()
	io.WriteString(t, url)

	urlMd5 := hex.EncodeToString(t.Sum(nil))
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// 获取数据库,获取集合
	c := session.DB("go_spider").C("History")

	count, err := c.Find(bson.M{"md5": urlMd5}).Count()
	if err != nil {
		panic(err)
	}

	if count > 0 {
		result = true
	} else {
		history := &MHistory{Id: bson.NewObjectId(), Url: url, Md5: urlMd5, State: Pending, LastModifyTime: time.Now()}

		err = c.Insert(history)

		if err != nil {
			panic(err)
		}
		result = false
	}
	return result
}
func (this *MongodbHistory) Update(url string, state string, lastModifyTime time.Time) {
	//this.locker.Lock()
	//defer this.locker.Unlock()
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		panic(err)
	}
	defer session.Close()
	t := md5.New()
	io.WriteString(t, url)

	urlMd5 := hex.EncodeToString(t.Sum(nil))
	// 获取数据库,获取集合
	c := session.DB("go_spider").C("History")

	colQuerier := bson.M{"md5": urlMd5}
	change := bson.M{"$set": bson.M{"State": state, "LastModifyTime": lastModifyTime}}
	err = c.Update(colQuerier, change)
	if err != nil {
		panic(err)
	}
}
